var jbDesigner=null;

JB.SelectTool=
{
  onChangeRect : function (e, dragElement)
  {
    rect = JavaBase.Dimension.getInnerElementRect(dragElement);
    bigRect = JavaBase.Dimension.getInnerElementRect(JB.SelectTool.selectElement);
  },

  unselect : function(e)
  {
    if(this.selectElement)
    {
      this.selectElement.removeChild(this.centerd);
      this.centerd=null;
      this.selectElement=null;
    }
  },
  
  select: function (e, divEle)
  {
    if(this.selectElement)
      return;

    this.selectElement= divEle;

    this.centerd = document.createElement('div');
    this.centerd.id = "centerd";
    
    rect = JavaBase.Dimension.getElementRect(divEle);
    
    aStyle = this.centerd.style;
    aStyle.position = 'absolute';
    aStyle.left=rect.left+"px";
    aStyle.top=rect.top+"px";
    aStyle.width=rect.width+"px";
    aStyle.height=rect.height+"px";
    //aStyle.border="1px green dashed";
    
    JavaBase.DomUtil.setAttributeValue(this.centerd, "draggable", "true");
    JavaBase.DomUtil.setAttributeValue(this.centerd, "onDrag_Drag", "JB.RectTool.onChangeRect");
    JavaBase.DomUtil.setAttributeValue(this.centerd, "onResize", "JB.RectTool.onChangeRect");
    JavaBase.DomUtil.setAttributeValue(this.centerd, "resizable", "true");
    document.body.appendChild(this.centerd);
  }
}

function JBDesigner()
{
  this.selected = null;
  this.selectedId=null;
  this.palette = null;

  this.piWindow=null;
  this.initialize = function() {
      if(!top.designer) {
          
      }
  }

  this.refreshPropertyInspector = function (id)
  {
    leftPos = 0;
    if(screen)
    {
      leftPos = screen.width-260
    }
    
    if(!top.designer)
    {
        editURL = "piRegion.xsp?pageMode=inspector&id=" + id;
        this.piWindow =  window.open(editURL, 'PropertyInspector',
            'scrollbars=yes,resizable=no,toolbar=no,height='+screen.width+', width=260,left='+leftPos+',top=0');
  
        if(this.piWindow)
        {
            if(this.piWindow.opener == null || this.piWindow.opener!= window) 
            {
                this.piWindow.opener = window;
                this.piWindow.opener.name = "newPUMain";
            }
        }
        return false;
    }else {
        editURL = "piRegion.xsp?pageMode=inspector&id=" + id;
        top.designer.location.href = editURL;
    }
  };

//this is called when it is design mode and there is an element selected

  this.defaultDesignOnLoad = function ()
  {
    jbMenus.timeout = 50000;
    if(this.selectedId != null )
    if($(this.selectedId))
    {
      this.oldBorder = $(this.selectedId).style.border;
      $(this.selectedId).style.border="1px red dashed";
     // JB.SelectTool.select(e, this.selectedId);        
     // $(this.selectedId).setAttribute('onDrag_End',"jbDesigner.onDragEnd");
     // $(this.selectedId).setAttribute('onDrag_',"JB.onDrag");
     // $(this.selectedId).setAttribute('onDrag_Begin','JB.onDragBegin');
    //  $(this.selectedId).setAttribute('clone',true);
    }
    this.showPI();
    JavaBase.EventFactory.registerKeypressListener(document, jbDesigner.onKeyPressed);
  };
  
  this.initializeRuntime = function ()
  {
    this.hidePI();
  };
  /**
   * This is called by the property editor when property changes the component
   */
  this.onChangeProperty = function(ele)
  {
  //framemode
    if(top.main)
    {
        mainEle=$('main');
        if(mainEle) {
            this.selectedId=ele;
            JB.renderChildren('main',{callback: function()
                {       
                    jbDesigner.defaultDesignOnLoad();
                }}
            );
        }else
            top.main.location.href = top.main.location.href;
    }else
    {
        mainEle=$('main');
        if(mainEle) {
            JB.renderChildren('main');
        }else
            JBUtil.reload(); 
    }
  };
  
  this.unselect = function(e)
  {
    if(this.selectedId != null )
    if($(this.selectedId))
    {
      
      $(this.selectedId).style.border=this.oldBorder;
     // JB.SelectTool.select(e, this.selectedId);        
     // $(this.selectedId).setAttribute('onDrag_End',"jbDesigner.onDragEnd");
     // $(this.selectedId).setAttribute('onDrag_',"JB.onDrag");
     // $(this.selectedId).setAttribute('onDrag_Begin','JB.onDragBegin');
      $(this.selectedId).setAttribute('clone',false);
    }
  };

  this.onDragEnd = function(event, dragElement)
  {
      var pt = JavaBase.EventFactory.getPosition(event);
      var ele = JavaBase.Dimension.getElementsByPosition(pt);      
      
      if(ele && ele.length > 1 && jbDesigner&&this.selectedId)
      {
        if(ele[1].id != $(this.selectedId).parentNode.id)
         jbDesigner.jbMove( ele[1].id);
      }
  };
  
  this.toggleMBBox=function(e, pageId)
  {
    $('jbVariableBox').style.display='none';
    JB._e(JBUtil.getUrl(), pageId, "${jb:assign(session, 'showManagedBean', false)}");
    Event.stop(e); 
  };
  
  this.toggleDesignMode=function(e, pageId)
  {
    JBUtil.gotoUrl(pageId);
    Event.stop(e); 
  };
  this.toggleDebug=function(e)
  {
    if(JBDebugger)
    {
        JBDebugger.toggleDebug();
    }
  };
  this.openDesigner=function(e)
  {
    JBUtil.gotoUrl('designer.xsp');
    Event.stop(e);
  };
  
  this.openConfig=function(e)
  {
    JBUtil.gotoUrl('jbConfig.xsp');
    Event.stop(e);
  };

  this.togglePI = function() {
    if(top)
    {
        this.isPIVisible=!this.isPIVisible;
        if(this.isPIVisible)
            this.hidePI();
        else
            this.showPI();
    }
  };

  this.hidePI = function() {
    if(top)
    {
        var frameset = top.document.getElementById("javabase");
        if(frameset)
        {
            frameset.origCols = frameset.cols;
            frameset.cols = "*, 0%";
        }
    }
  };
  
  this.showPI = function() {
    if(top)
    {
        var frameset = top.document.getElementById("javabase");
        if(frameset)
        {
          //  frameset.cols = frameset.origCols?frameset.origCols:"15%, *, 20%";
            frameset.cols = "*, 260px";
        }
    }
  };
  
  this.selectPalette = function(e)
  {
    var sourceEle = JavaBase.EventFactory.getEventSource(e);
    this.palette = JavaBase.DomUtil.getAttributeValue(sourceEle, 'sourceId');
  } ;

  this.addEle = function (e, parentId)
  {
    var location = JBUtil.getUrl()+'?itemType=' + this.palette +'&id='+ parentId;
    JB._e(location, parentId, "com.jb.web.application.event.ComponentEH.onAddComponent", parentId, null,
        function(transport)
        {
            var response  = transport.responseText;
            try
            {
                try{
                    if(response.indexOf("pageName")!=-1)
                    {
                        var p = eval("(" + response + ")");
                        if(p.pageName)
                        {
                            JB.showDialogBox(p.pageName,p.panelName);
                            jbDesigner.wizard=true;
                            return false;
                        }
                    }else
                        return true;
                }catch (e)
                {
                  // alert(e);
                }
                return true;
            }catch(e)
            {
                return true;
            }
        }
    );
  };
  
  this.createComponent = function(e, ele)
  {
    jbDesigner.palette = JavaBase.DomUtil.getAttributeValue(ele, 'sourceId')
    currentCursorPt= JavaBase.EventFactory.getPosition(e);
     
    var eles = JavaBase.Dimension.getElementsByPosition(currentCursorPt);
    
    eles[eles.length]=document.body;

    for(i= 0; i<eles.length;i++)
    {
      if(JavaBase.DomUtil.getAttributeValue(eles[i], 'ondrop')=='true')
      {
        jbDesigner.addEle(e, eles[i].id);
        break;
      }
    }
  };
  /**
   * Selects the component by client id for design
   * 
   */
  this.select = function(e, url, id, clientId, cancelEvent)
  {
    
    if(!!this.wizard) return;
    
    if(!cancelEvent)
        Event.stop(e);
    
    this.unselect();
    
    if(!cancelEvent)
        JavaBase.EventFactory.cancelBubbleFor(e);
    if(JavaBase.EventFactory.getButton(e) != JavaBase.EventFactory.BUTTON_LEFT)
    {
      return;
    }
    
    if(this.selected)
    {
      if(clientId==this.selected.id)
        return ;
    }
    this.selected =$(clientId);
    this.selectedId=clientId;
  //  this.defaultDesignOnLoad();
    jbDesigner.refreshPropertyInspector(id);    
  };
  
  this.jbMove = function(parentId)
  { 
    return;
    /*
    selected=$(this.selectedId);
    if(selected.tagName=='TD')
      return;
    if(selected.tagName=='TR')
      return;
      
    if(parentId==selected.id)
      return;
      
    var parent =selected.parentNode;
   
    if(parent.id!=parentId)
    {
      parent.removeChild(selected);
      $(parentId).appendChild(selected);
      JB._e(JBUtil.getUrl()+'?moveToId='+parentId+'&action=com_jb_design_move', 
        parentId,'com.jb.web.bean.event.CommandManager');        
    }*/
  };
  this.jbCopy = function()
  {
    JB._e(JBUtil.getUrl(),'com_jb_design_copy','com.jb.web.bean.event.CommandManager');        
  };
  
  this.jbCut = function()
  {
    JB._e(JBUtil.getUrl(),'com_jb_design_cut','com.jb.web.bean.event.CommandManager');        
  };
  
  this.jbPaste = function()
  {
    JB._e(JBUtil.getUrl(),'com_jb_design_paste','com.jb.web.bean.event.CommandManager');        
  };
  
  
  this.deleteSelected = function()
  {
    selected=$(this.selectedId);
    var parent =selected.parentNode;
    parent.removeChild(selected);
    JB._e(JBUtil.getUrl(),'com_jb_design_delete','com.jb.web.bean.event.CommandManager',parent.id);        
  };
  
  this.onKeyPressed = function(e)
    {
       var key  = JavaBase.EventFactory.getKey(e);
       var charCode  = JavaBase.EventFactory.getChar(e);
    
       ///altKey, ctrlKey, shiftKey
       if(e.ctrlKey && charCode!=17)
       {
        if(charCode==67||charCode==99)
          jbDesigner.jbCopy();
        if(charCode==88||charCode==120)
          jbDesigner.jbCut();
        if(charCode==86||charCode==118)
          jbDesigner.jbPaste();

        if(charCode==82||charCode==114)
          jbDesigner.toggleDesignMode(e, JBUtil.getUrl()+'?editAction=changeMode');
      }
        if(key==46)
          jbDesigner.deleteSelected();
  };
  
  this.toggleDesignPad = function(evt)
  {
    var pt = JavaBase.EventFactory.getPosition(evt);
    var windowRect = JavaBase.Dimension.getWindowRect();
    if($('designPad'))
    {
        var rect = JavaBase.Dimension.getElementRect($('designPad'));
        if(pt.left >(windowRect.width - rect.width - 2) && pt.left<windowRect.width && pt.top>0&&pt.top<10)
        {
            $('designPad').style.left = (windowRect.width - rect.width - 2)+'px';
            Element.show('designPad');
        }else if(pt.top>30)
        {
            Element.hide('designPad');        
        }
    }
  }
}

//wizard library
//Widard starts when one drop a component that has a wizard registered against it
//The component will not be created, instead, a wizard will be created 
//and stored on the session. The wizard would prompt a form the is designed
//for the wizard. Wizard form should call one of these methods to perform wizard
//function
//when submit is clicked, the wizard should create the component, and close.
//
JB.Wizard =
{
    cancel :function(formCompId, reqCompId)
    {   
      formId='f'+formCompId;
      url = $(formId).action;
      url = url+ '&editAction=wizard.cancel&' + JB.REQ_COMP_ID 
        + '=' + formCompId + '&' + JB.RES_COMP_ID+'='+reqCompId;   
    
      url = url+ '&'+Form.serialize(formId);
    
      JB.Ajax.post(url, '', 
        function (transport)
        {
          try
          {
            JB.hideDialogBox(reqCompId);
            jbDesigner.wizard=false;
            //JB.StateMachine.rerender(reqCompId, transport.responseText);
          }catch( e)
          {
            JBUtil.reload();
          }
        }, null, null
      );
    },

    next :function(formCompId, reqCompId)
    {
      formId='f'+formCompId;
      url = $(formId).action;
      url = url+ '&editAction=wizard.next&' + JB.REQ_COMP_ID 
        + '=' + formCompId + '&' + JB.RES_COMP_ID+'='+reqCompId;   
    
      url = url+ '&'+Form.serialize(formId);
    
      JB.Ajax.post(url, '', 
        function (transport)
        {
          try
          {
            JB.StateMachine.rerender(reqCompId, transport.responseText);
          }catch( e)
          {
            JBUtil.reload();
          }
        }, null, null
      );
   },
    submit :function(formCompId, reqCompId)
    {
      formId='f'+formCompId;
      url = $(formId).action;
      
      url = url+ '&editAction=wizard.submit&' + JB.REQ_COMP_ID 
        + '=' + formCompId + '&' + JB.RES_COMP_ID+'='+reqCompId;   
    
      url = url+ '&'+Form.serialize(formId);
    
      JB.Ajax.post(url, '', 
        function (transport)
        {
          try
          {
          //  JB.hideDialogBox(reqCompId);
          //  jbDesigner.wizard=false;
            JBUtil.reload();
            //render the component that new component has been added to
            //TODO
            
          }catch( e)
          {
            JBUtil.reload();
          }
        }, null, null
      );
   }
};


jbDesigner = new JBDesigner();

JavaBase.EventFactory.registerMousemoveListener(document, jbDesigner.toggleDesignPad);
